<%-- 
    Document   : ReadFile
    Created on : Feb 27, 2015, 5:42:54 PM
    Author     : user
--%>

<%@page import="newpackage.SplitFileExample"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.util.Random"%>
<%@page import="java.io.FileReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.File"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="newpackage.ConnectionFactory"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Read File</title>
        
        <script type="text/javascript">
            function readSubmit()
            {
                document.read_file.action="./SaveContent.jsp";
                document.read_file.submit();
            }
        </script>
    </head>
    <body background="image.jpg">
        <form name="read_file" method="post" align="center">
        <%
String fname=request.getParameter("file_name");        
String timestamp1=request.getParameter("timestamp1");        
String timestamp2=request.getParameter("timestamp2");    


SimpleDateFormat format =  new SimpleDateFormat("yyyy/MM/dd HH:mm");
String name=fname.substring(fname.lastIndexOf('/')+1);
session.setAttribute("name_only", name);
Date Start_date=format.parse(timestamp1);
Date End_date=format.parse(timestamp2);

Connection con=ConnectionFactory.getConnection();
Statement s=con.createStatement();
String query="Select * from update_values where time_stamp between '"+timestamp1+"' and '"+timestamp2+"' and name LIKE '%"+name+"%'";
//out.println(query);
//System.out.print(query);
String file_name="";
String Site="";
ResultSet rs=s.executeQuery(query);
boolean flag=false;
while(rs.next())
       {
    flag=true;
    file_name=rs.getString("name");
    Site=rs.getString("readsite");
}
if(flag)
       {
String path=getServletContext().getRealPath(Site);
session.setAttribute("path", path);
out.println("<textarea name='file_content' rows='30' cols='150'>");
// BufferedReader br=new BufferedReader(new FileReader(path+"/"+name)) ;  
if(file_name!=null)
       {
BufferedReader br=new BufferedReader(new FileReader(file_name));
       String line;
while((line=br.readLine())!=null)          
       {
    out.println(line);
       }
             }
else
       {
    out.println("File not found");
}
    out.println("</textarea>");   
}
else
{
    out.println("File not found");
}
%>
<p align='center'><input type="submit" value="submit" /></p>
    </form>
<p align="center"><a href="ViewFile_1_1.jsp" >Back</a></p>
<p align="center"><a href="Login.jsp" align="center">Logout</a></p>


    </body>
    <%!int version=1;%>
    <%
      String no=(String)session.getAttribute("name_only");
    Connection co=ConnectionFactory.getConnection();
   ResultSet rs2=con.createStatement().executeQuery("SELECT MAX(VERSION) FROM update_values WHERE NAME LIKE '%"+no+"%'");
   if(rs2.next())
   {
   version=rs2.getInt(1);    
   }
     String q;
if(request.getParameter("file_content")!=null)
{
StringBuffer sb=new StringBuffer();
sb.append(request.getParameter("file_content"));

Random random = new Random();
      int rand= random.nextInt((10 - 1) + 1) + 1;
       if(rand<=5)
      {     String p=getServletContext().getRealPath("/");

           
 
			// if file doesnt exists, then create it
		String ret=createFile(p+"read/"+no);
                File file = new File(ret);
 String time="";
 time=format.format(new Date());
     String newpath=file.getAbsolutePath().replace("\\","/");
q="insert into update_values(name,version,ReadSite,Time_stamp) values ('"+newpath+"',"+version+",'read','"+time+"')";
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(sb.toString());
			bw.close();
 
			System.out.println("File writed in read site");
       }
      else
                   {
           String p=getServletContext().getRealPath("/");
 // String no=(String)session.getAttribute("name_only");
          
 
			// if file doesnt exists, then create it
           
			String ret=createFile(p+"read1/"+no);
                  File file = new File(ret);
                  
                   String time="";
 time=format.format(new Date());
      String newpath=file.getAbsolutePath().replace("\\","/");
q="insert into update_values(name,version,ReadSite,Time_stamp) values ('"+newpath+"',"+version+",'read1','"+time+"')";
         
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(sb.toString());
			bw.close();
 
			System.out.println("File writed in read1 site");
          
      }
      
      Connection c=ConnectionFactory.getConnection();
      c.createStatement().execute(q);
      
         String p=getServletContext().getRealPath("/");
   //      String no=(String)session.getAttribute("name_only");
         
     File file = new File(p+"/sub/"+no);
       File file1 = new File(p+"/update/"+no);
             File file2 = new File(p+"/update1/"+no);
     
     
        
      // creates the file
          file.createNewFile();
          file1.createNewFile();
          file2.createNewFile();
      // creates a FileWriter Object
         FileWriter writer = new FileWriter(file); 
         FileWriter writer1 = new FileWriter(file1);
         FileWriter writer2 = new FileWriter(file2);          
         
      // Writes the content to the file
         writer.write(sb.toString()); 
         
         writer1.write(sb.toString()); 
         
       
         writer2.write(sb.toString()); 
         
         writer.flush();
         writer1.flush();
         writer2.flush();
         SplitFileExample.split(file.getAbsolutePath());
           SplitFileExample.split(p+"update/"+no);
         SplitFileExample.split(p+"update1/"+no);
       
         
writer.close();  
writer1.close();
writer2.close();
         
out.println("<script type='text/javascript'>");
out.println("alert('File Saved')");
out.println("</script>");
          
}

%>
    <%!int count=0;%>
    <%!
public String createFile(String name) throws IOException
  {
    String t="";
    File f;
    f = new File(name);
    if (!f.exists())
    {
      f.createNewFile();
    }
    else
    {
      count++;
     createFile(name + (count));
    
    t=name + (count);
    version=count;
    }
   return t;
  }
%>
</html>
